<template>
  <view class="my-cer">
    <view class="my-top">
      <view class="content">
        <u--form
          labelPosition="left"
          :model="userInfo"
          :rules="rules"
          ref="form1"
          :borderBottom="true"
        >
          <view class="front-box">
            <u-form-item
              label="身份证正面"
              prop="frontPhoto"
              :borderBottom="false"
            >
              <view class="img-view" v-if="picFrontList.length">
                <view v-for="(item, i) in picFrontList" :key="i">
                  <view class="del" @click="delFun(i, 'front')" v-if="!flag">
                    <u-icon name="close" color="#FFF" size="8"></u-icon>
                  </view>
                  <u--image
                    v-if="!flag"
                    :src="item.url"
                    width="100px"
                    height="100px"
                  ></u--image>
                  <u-album
                    v-if="flag"
                    singleSize="100px"
                    :urls="[
                      {
                        src1: item.url,
                      },
                    ]"
                    keyName="src1"
                  ></u-album>
                </view>
              </view>
              <view v-else class="upload-icon" @click="uploadFun('1')">
                <u-icon name="plus" color="#f39d21" size="28"></u-icon>
              </view>
            </u-form-item>
          </view>
          <view class="front-box">
            <u-form-item
              label="身份证反面"
              prop="frontPhoto"
              :borderBottom="false"
            >
              <view class="img-view" v-if="picBackList.length">
                <view v-for="(item, i) in picBackList" :key="i">
                  <view class="del" @click="delFun(i, 'back')" v-if="!flag">
                    <u-icon name="close" color="#FFF" size="8"></u-icon>
                  </view>
                  <u--image
                    :src="item.url"
                    v-if="!flag"
                    width="100px"
                    height="100px"
                  ></u--image>
                  <u-album
                    v-if="flag"
                    singleSize="100px"
                    :urls="[
                      {
                        src2: item.url,
                      },
                    ]"
                    keyName="src2"
                  ></u-album>
                </view>
              </view>
              <view v-else class="upload-icon" @click="uploadFun('2')">
                <u-icon name="plus" color="#f39d21" size="28"></u-icon>
              </view>
            </u-form-item>
          </view>
          <view class="pop-name">
            <u-form-item :borderBottom="true" label="姓名" prop="realName">
              <u--input
                placeholder="请输入"
                v-if="!flag"
                v-model="userInfo.realName"
                border="none"
                maxlength="20"
              ></u--input>
              <view v-else>{{ dealNum("name", userInfo.realName) }}</view>
            </u-form-item>
            <u-form-item :borderBottom="false" label="身份证号码" prop="number">
              <u--input
                placeholder="请输入"
                v-if="!flag"
                maxlength="20"
                type="idcard"
                v-model="userInfo.number"
                border="none"
              ></u--input>
              <view v-else>{{ dealNum("card", userInfo.number) }}</view>
            </u-form-item>
          </view>
        </u--form>
      </view>
    </view>

    <u-popup :show="showPop" @close="close">
      <view class="pop-box">
        <view class="pop-item" @click="uploadPicFun1">
          <u-icon name="photo" color="#f39d21" size="28"></u-icon>
          <view class="pop-t">本地照片</view>
        </view>
        <view class="pop-item" @click="uploadPicFun2">
          <u-icon name="weixin-circle-fill" color="#f39d21" size="28"></u-icon>
          <view class="pop-t">微信图片</view>
        </view>
      </view>
    </u-popup>

    <view class="sub1">
      <u-button
        v-if="
          !flag &&
          userInfo.backPhoto &&
          userInfo.frontPhoto &&
          userInfo.number.trim() &&
          userInfo.realName.trim()
        "
        @click="getSubmit"
        type="primary"
        text="提 交"
      ></u-button>
      <u-button v-else type="primary" disabled="disabled">{{
        flag ? "已实名认证" : "提 交"
      }}</u-button>
    </view>
  </view>
</template>

<script>
const app = getApp();
const globalData = app.globalData;
const wxImg = globalData.wxImg;
const apiUrl = globalData.wxApi;
import { getStoreData, dealNum, httpPost, httpGet } from "@/utils/http.js";
const pic1 = require(`@/img/my/my1.png`);
export default {
  data() {
    return {
      flag: false,
      showPop: false,
      name: "",
      dealNum,
      picBackList: [],
      picFrontList: [],
      userInfoNew: {},
      userInfo: {
        backPhoto: "",
        frontPhoto: "",
        number: "",
        realName: "",
      },
      rules: {
        realName: [
          {
            require: true,
            message: "请输入姓名",
            trigger: ["blur", "change"],
          },
        ],
        frontPhoto: [
          {
            require: true,
            message: "请上传身份证正面",
            trigger: ["blur", "change"],
          },
        ],
        backPhoto: [
          {
            require: true,
            message: "请上传身份证正面",
            trigger: ["blur", "change"],
          },
        ],
        number: [
          {
            require: true,
            len: 18,
            message: "请输入18位身份证号",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.idCard(value);
            },
            message: "请输入正确的身份证号",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  onLoad() {
    const userInfoNew = getStoreData("userInfo");
    if (userInfoNew && userInfoNew.realName) {
      this.flag = true;
      this.getData();
      // wx.setNavigationBarTitle({
      //   title: "修改认证",
      // });
    } else {
      this.flag = false;
    }
  },
  methods: {
    delFun(index, v) {
      if (v === "front") {
        this.picFrontList.splice(index, 1);
        this.userInfo.frontPhoto = "";
      } else {
        this.picBackList.splice(index, 1);
        this.userInfo.backPhoto = "";
      }
    },
    getData() {
      const _this = this;
      httpGet("/api/userverify/info")
        .then((res) => {
          _this.userInfoNew = res.data;
          _this.userInfo.frontPhoto = res.data.frontPhoto;
          _this.userInfo.backPhoto = res.data.backPhoto;
          _this.userInfo.realName = res.data.realName;
          _this.userInfo.number = res.data.number;
          _this.picFrontList = [
            {
              status: "success",
              message: "",
              url: `${wxImg + res.data.frontPhoto}`,
            },
          ];
          _this.picBackList = [
            {
              status: "success",
              message: "",
              url: `${wxImg + res.data.backPhoto}`,
            },
          ];
        })
        .catch((e) => {
          //
        });
    },
    getSubmit() {
      const _this = this;
      this.$refs.form1.validate().then((res) => {
        _this.getSubmit1();
      });
    },
    getSubmit1() {
      const _wx = wx;
      httpPost(
        this.flag ? "/api/userverify/userUpdate" : "/api/userverify/apply",
        this.userInfo
      )
        .then((res) => {
          uni.showToast({
            title: "提交成功",
            icon: "none", //默认success
            duration: 1500,
          });
          setStoreData("aboutMe", true);
          setTimeout(() => {
            uni.navigateBack({
              delta: 1, // 返回上一级页面。
            });
          }, 1500);
        })
        .catch((e) => {});
    },
    uploadPicFun2: function (tempFile) {
      const _this = this;
      wx.chooseMessageFile({
        count: 1,
        type: "all",
        success(res) {
          const newTemp = res.tempFiles;
          _this.uploadFileFun(newTemp[0].path, newTemp[0].name);
        },
      });
    },
    uploadFileFun(path, name) {
      const _this = this;
      wx.showLoading({ title: "图片上传中" });
      wx.uploadFile({
        url: apiUrl + "/api/upload/userPhoto",
        filePath: path,
        name: "file",
        success: function (res) {
          const data = JSON.parse(res.data);
          if (data.code === 0 && data.data && data.data[0]) {
            const pic = data.data[0].path + "/" + data.data[0].name;
            if (_this.name === "1") {
              _this.userInfo.frontPhoto = pic;
              _this.picFrontList = [
                {
                  status: "success",
                  message: "",
                  url: `${wxImg + pic}`,
                },
              ];
            } else {
              _this.userInfo.backPhoto = pic;
              _this.picBackList = [
                {
                  status: "success",
                  message: "",
                  url: `${wxImg + pic}`,
                },
              ];
            }
            _this.showPop = false;
          } else {
            uni.$u.toast("上传失败，请重新上传");
          }
          uni.hideLoading();
        },
        fail: function (err) {
          uni.$u.toast("上传失败，请重新上传");
          uni.hideLoading();
        },
      });
    },
    uploadPicFun1(e) {
      const _this = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"], //原图或者压缩图
        sourceType: ["album", "camera"], //图片，还是相机
        success: function (res) {
          const tempFiles = res.tempFiles;
          let flag = false;
          const newTemp = tempFiles.map((i, k) => {
            const name = Date.parse(new Date());
            const path = i.path;
            const picType = path
              .split(".")
              [path.split(".").length - 1].toLowerCase();
            if (
              ["png", "jpg", "jpeg", "gif"].includes(picType) &&
              i.size <= 20 * 1024 * 1024
            ) {
              // 如果是图片且小于20M，不处理
            } else {
              flag = true;
            }
            return { ...i, name: name + k + "." + picType };
          });
          if (flag) {
            uni.$u.toast("请上传图片格式且大小不超过20M");
            return;
          }
          for (let i = 0; i < newTemp.length; i++) {
            uni.showLoading({ title: "图片上传中" });
            uni.uploadFile({
              url: apiUrl + "/api/upload/userPhoto",
              filePath: newTemp[i].path,
              name: "file",
              // header: {
              //   "content-type": "application/json",
              //   Authorization: getStoreData("token") || "",
              // },
              // formData: {
              //   fileName: newTemp[i].name,
              // },
              success: function (res) {
                const data = JSON.parse(res.data);
                if (data.code === 0 && data.data && data.data[0]) {
                  const pic = data.data[0].path + "/" + data.data[0].name;
                  if (_this.name === "1") {
                    _this.userInfo.frontPhoto = pic;
                    _this.picFrontList = [
                      {
                        status: "success",
                        message: "",
                        url: `${wxImg + pic}`,
                      },
                    ];
                  } else {
                    _this.userInfo.backPhoto = pic;
                    _this.picBackList = [
                      {
                        status: "success",
                        message: "",
                        url: `${wxImg + pic}`,
                      },
                    ];
                  }
                  _this.showPop = false;
                } else {
                  uni.$u.toast("上传失败，请重新上传");
                }
                uni.hideLoading();
              },
              fail: function (err) {
                uni.$u.toast("上传失败，请重新上传");
                uni.hideLoading();
              },
            });
          }
        },
      });
    },
    close() {
      this.showPop = false;
    },
    uploadFun(v) {
      this.name = v;
      this.showPop = true;
    },
    // getInfo() {
    //   const _this = this;
    //   httpGet("/api/user/info")
    //     .then((res) => {
    //       // _this.storeInfo = res.data;
    //     })
    //     .catch((e) => {
    //       //
    //     });
    // },
  },
};
</script>

<style lang="scss">
.my-cer {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: #f8f8f8;
  width: 100vw;
  min-height: 100vh;
  padding: 16px;
  .pop-name {
    margin: 16px 0 0;
    /deep/.u-form-item__body {
      display: flex !important;
    }
  }
  .sub1 {
    margin: 36px 0;
    /deep/.u-button {
      width: calc(100% - 48px);
      height: 50px;
      line-height: 50px;
      font-size: 16px;
    }
  }
  .img-view {
    position: relative;
    .del {
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      border-bottom-left-radius: 100px;
      z-index: 99;
      background: #444;
      height: 14px;
      width: 14px;
      justify-content: flex-end;
      /deep/.u-icon--right {
        padding: 2px;
      }
    }
  }
  .front-box {
    /deep/.u-form-item__body {
      display: flex;
      flex-direction: column !important;
      .u-form-item__body__right {
        width: 100px;
        height: 100px;
        margin-top: 16px;
        justify-content: center;
        align-items: center;
        .u-image__image {
          border: 1px solid #eee;
        }
        .upload-icon {
          .u-icon__icon {
            border: 1px solid #eee;
            width: 100px;
            height: 100px;
            justify-content: center;
          }
        }
      }
    }
  }
  .pop-box {
    display: flex;
    justify-content: center;
    align-items: center;
    .pop-item {
      display: flex;
      flex-direction: column;
      width: 40%;
      padding: 32px 0 16px 0;
      align-items: center;
      .pop-t {
        margin-top: 8px;
        font-size: 14px;
        color: #333;
      }
    }
  }
  .content {
    background: #fff;
    border-radius: 4px;
    padding: 0 16px;
    box-sizing: border-box;
    margin-bottom: 16px;
    flex-direction: column;
    width: calc(100vw - 32px);
    /deep/.u-cell__body {
      padding: 16px 0 !important;
    }
    /deep/.u-form-item__body__left {
      min-width: 90px;
    }
  }
  .u-slot-title1 {
    display: flex;
    flex-direction: column;
    .u-cell1 {
      font-size: 16px;
      line-height: 30px;
      color: #333;
    }
    .u-cell2 {
      font-size: 14px;
      margin-left: 6px;
      line-height: 30px;
      color: #f39d21;
    }
    .u-cell3 {
      font-size: 14px;
      line-height: 30px;
      color: #999;
      min-width: 50px;
    }
    .u-cell4 {
      font-size: 14px;
      line-height: 30px;
      color: #333;
    }
  }
  .my-top {
    display: flex;
    flex-direction: column;
    width: 100%;
    .ava {
      width: 40px;
      height: 40px;
      border-radius: 40px;
      overflow: hidden;
    }
  }
}
</style>
